package net.lab1024.sa.admin.module.yitihua.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import net.lab1024.sa.admin.module.yitihua.*;
import net.lab1024.sa.admin.module.yitihua.dao.Cfs119HouseDao;
import net.lab1024.sa.admin.module.yitihua.domain.entity.Cfs119House;
import net.lab1024.sa.admin.module.yitihua.domain.form.Cfs119HouseAddForm;
import net.lab1024.sa.admin.module.yitihua.domain.form.Cfs119HouseQueryForm;
import net.lab1024.sa.admin.module.yitihua.domain.form.Cfs119HouseUpdateForm;
import net.lab1024.sa.admin.module.yitihua.domain.vo.Cfs119HouseVO;
import net.lab1024.sa.base.common.domain.PageResult;
import net.lab1024.sa.base.common.domain.ResponseDTO;
import net.lab1024.sa.base.common.util.SmartBeanUtil;
import net.lab1024.sa.base.common.util.SmartPageUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * 一体化平台户信息 Service
 *
 * @Author cfsjiazy
 * @Date 2025-09-12 11:55:01
 * @Copyright  
 */

@Service
@Slf4j
public class Cfs119BaseService {

    @Value("${integration.event.url:http://xfzhjg.bj.119.gov.cn/xfjgfw-xfjg}")
    private String URL;
    @Value("${integration.event.bjxfappId:22041288f3673e35b73a20e8b0c9b030}")
    private String bjxfappId;
    @Value("${integration.event.rsign:367y0k37r3094725}")
    private String rsign;
    // 缓存的token
    private String cachedToken;
    // token的获取时间
    private long tokenFetchTime;
    // token有效期，单位：毫秒
    private static final long TOKEN_EXPIRATION_TIME = 5 * 60 * 1000;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;


    public <T> List<T> getDataByServiceCode(Cfs119Param param, String serviceCode, Class<T> clazz) {
        String bjxfrtime = String.valueOf(System.currentTimeMillis());
        String token = getToken(bjxfrtime);

        HttpHeaders headers = new HttpHeaders();
        headers.add("bjxfappId", bjxfappId);
        headers.add("bjxfrtime", bjxfrtime);
        headers.add("bjxfrsign", SM4Utils.encryptData_ECB(bjxfrtime, token));
        headers.add("Accept", "application/json");
        headers.add("Content-Encoding", "UTF-8");
        headers.add("Content-Type", "application/json");

        String url = URL + "/rest/open/microService.do?serviceCode=" + serviceCode;
        JSONObject response = RestTemplateUtil.post(headers, url, JSONObject.toJSONString(param));

        if (response != null && "0".equals(response.getString("returnCode"))) {
            String totalCount = response.getString("totalCount");
            log.info("该接口共 {} 条数据", totalCount);
            JSONArray data = response.getJSONArray("data");
            List<T> list = data.toJavaList(clazz);
            log.info("【{}】调用成功，获取数据 {} 条", serviceCode, list.size());
            return list;
        } else {
            log.error("【{}】调用失败，响应内容: {}", serviceCode, response);
            return new ArrayList<>();
        }
    }

    private String getToken(String bjxfrtime) {
        // 检查缓存的token是否有效
        if (cachedToken != null && System.currentTimeMillis() - tokenFetchTime < TOKEN_EXPIRATION_TIME) {
            log.info("一体化平台--使用缓存的token");
            return cachedToken;
        }
        JSONObject header = new JSONObject();
        header.put("bjxfappId", bjxfappId);
        header.put("bjxfrtime", bjxfrtime);
        header.put("bjxfrsign", SM4Utils.encryptData_ECB(String.valueOf(bjxfrtime), rsign));
        JSONObject result = null;
        try {
            result = HttpUtil.httpGet(URL + "/rest/client/token.do", header);
        } catch (Exception e) {
            log.error("一体化平台--获取token失败{}", e.getMessage());
            throw new RuntimeException(e);
        }
        String token = null;
        if (result.getInteger("responseCode") == 200) {
            JSONObject data = JSONObject.parseObject(result.getString("responseString"));
            if ("0".equals(data.getString("returnCode"))) {
                token = SM4Utils.decryptData_ECB(data.getString("token"), rsign);
                // 缓存新的token和获取时间
                cachedToken = token;
                tokenFetchTime = System.currentTimeMillis();
                //存入redis
                redisTemplate.opsForValue().set("yitihua:token", token, TOKEN_EXPIRATION_TIME, TimeUnit.MILLISECONDS);
            }
        }
        return token;
    }

}
